<?php
declare(strict_types=1);

namespace app\shop\controller\worker;

use app\admin\library\Auth as AdminAuth;
use app\shop\library\ShopWorkerHelper;
use app\shop\service\NotifyService;
use app\worker\library\WorkerWsApp;
use think\App;
use think\db\exception\DbException;
use Throwable;

class NotifyController
{
    /**
     * 构造方法
     * @param WorkerWsApp $app 应用对象
     * @throws Throwable
     */
    public function __construct(protected App $app) { }

    /**
     * 绑定管理员
     * @return void
     * @throws Throwable
     * @throws DbException
     */
    public function bind(): void
    {
        $adminAuth  = AdminAuth::instance();
        $adminToken = $this->app->message['ba_token'] ?? '';
        $adminAuth->init($adminToken);

        if ($adminAuth->isLogin()) {
            $notifyService = new NotifyService();
            $adminUid      = $notifyService->getCacheAdminKey($adminAuth->id);
            ShopWorkerHelper::instance()
                ->bindUid($this->app->clientId, $adminUid)
                ->send($adminUid, 'bind', [
                    'message'  => '绑定成功',
                    'clientId' => $this->app->clientId,
                    'uid'      => $adminUid,
                ]);
            // 获取未读消息数
            if ($adminAuth->check('shop/notify/notify')) {
                $notifyService->unreadCount($adminAuth->id);
            }
        } else {
            $this->app->send('noLogin', [
                'message' => '请登录'
            ]);
        }
    }
}